#!/usr/bin/perl
#
# Installs the currently defined counter website as an Apache vhost.
#
# Author: Harald Alvestrand
# License: GPL
#
use strict;
use Getopt::Long;

my $test;

GetOptions("test|n" => \$test,
    );

if ( ! $ENV{"COUNTER_ROOT"}) {
   die "COUNTER_ROOT not set. Run . tools/runscript first\n"
}
if ( ! -d $ENV{"COUNTER_ROOT"}) {
   die "COUNTER_ROOT points to a nonexistent directory. Fix .counter.ini,\n"
       + "then rerun . tools/runscript\n";
}

# this could have been done with the Counter module, but that pulls in a
# very large amount of stuff, so skipping.
my $homedir = $ENV{"COUNTER_ROOT"};
my $website = $ENV{"COUNTER_HOST"};

my $apacheconf = "/etc/apache2/sites-available/$website";
if ($test) {
    open(APACHECONF, ">&1");
    warn "Test - writing to stdout, not to $apacheconf\n";
} else {
    open(APACHECONF, ">$apacheconf")
	|| die "Unable to write to Apache config file $apacheconf\n";
}
open(TEMPLATE, "$homedir/config/apacheconfig")
	       || die "Unable to source Apache config template\n";

# Substitute in variables from the environment as needed.
while (<TEMPLATE>) {
    while (s/\$([A-Z0-9_]+)/$ENV{$1}/) {
	die "Undefined variable $1" if !defined($ENV{$1});
    }
    print APACHECONF;
}
my $logdir = "/var/log/apache2/$website";
if (! -d $logdir) {
    if ($test) {
	warn "Must create $logdir\n";
    } else {
	mkdir($logdir) || die "Unable to create log directory $logdir\n";
    }
}
if (! -f "/etc/apache2/sites-enabled/$website") {
    if ($test) {
	warn "Must a2ensite $website\n";
    } else {
	# system returns 0, so must check with &&, not ||
	system("a2ensite $website") && die "Unable to a2enable $website\n";
    }
}
system("apache2ctl configtest") && die "Configuration test failed\n";
warn "You must do apache2ctl restart by hand\n";
